const Project = require('../models/project.model');
const sshService = require('../services/ssh.service');
const CryptoUtil = require('../utils/crypto');

exports.testServerConnection = async (req, res) => {
  try {
    const { serverConfig } = req.body;
    const result = await sshService.testConnection(serverConfig);
    res.json(result);
  } catch (error) {
    res.status(400).json({ success: false, message: error.message });
  }
};

exports.createProject = async (req, res) => {
  try {
    const projectData = { ...req.body };
    
    // 加密 SSH 私钥
    if (projectData.deploymentConfig?.serverConfig?.privateKey) {
      projectData.deploymentConfig.serverConfig.privateKey = 
        CryptoUtil.encrypt(projectData.deploymentConfig.serverConfig.privateKey);
      projectData.deploymentConfig.serverConfig.isEncrypted = true;
    }

    const project = new Project(projectData);
    await project.save();
    res.status(201).json(project);
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
};

exports.updateProject = async (req, res) => {
  try {
    const projectData = { ...req.body };
    
    // 如果更新了 SSH 私钥，需要重新加密
    if (projectData.deploymentConfig?.serverConfig?.privateKey &&
        (!projectData.deploymentConfig.serverConfig.isEncrypted ||
         projectData.deploymentConfig.serverConfig.privateKeyChanged)) {
      projectData.deploymentConfig.serverConfig.privateKey = 
        CryptoUtil.encrypt(projectData.deploymentConfig.serverConfig.privateKey);
      projectData.deploymentConfig.serverConfig.isEncrypted = true;
    }

    const project = await Project.findByIdAndUpdate(
      req.params.id,
      projectData,
      { new: true }
    );
    
    if (!project) {
      return res.status(404).json({ error: '项目不存在' });
    }
    res.json(project);
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
}; 